import fs from 'fs';

/** 预构建的依赖 */
export async function elementPlusStyleOptimizeIncludes(type: 'css' | 'scss'): Promise<string[]> {
  try {
    const elementPlusStylePath: string[] = [];
    // 得到 'element-plus/es/components' 目录下的所有目录名称
    const dirnames = fs.readdirSync('node_modules/element-plus/es/components');
    //得到需要检测的路径，防止导入不存在的路径
    const accessPaths = dirnames.map((dirname) => {
      const returnPath = `element-plus/es/components/${dirname}/style/${type === 'css' ? 'css' : 'index'}`; // 需要返回的路径
      const checkPath = `node_modules/${returnPath}.mjs`; // 需要检测的路径
      return getAccessPath(checkPath, returnPath);
    });
    // 得到所有路径（包含null）
    const paths = await Promise.all(accessPaths);
    // 去除null
    paths.forEach((path) => {
      path && elementPlusStylePath.push(path);
    });

    return Promise.resolve(elementPlusStylePath);
  } catch (error) {
    return Promise.resolve([]);
  }
}

/** 预构建的依赖 */
export async function optimizeIncludes(packages: string[]): Promise<string[]> {
  const includesPaths: string[] = [];

  //得到需要检测的路径，防止导入不存在的路径
  const accessPaths = packages.map((dirname) => {
    return getAccessPath(`node_modules/${dirname}`, dirname);
  });
  // 得到所有路径（包含null）
  const paths = await Promise.all(accessPaths);
  // 去除null
  paths.forEach((path) => {
    path && includesPaths.push(path);
  });

  if (includesPaths.length !== packages.length) {
    const notPath = packages.filter((v) => includesPaths.indexOf(v) === -1);
    console.log('以下依赖没有被预构建:', notPath);
  }
  return Promise.resolve(includesPaths);
}

/**
 * 检测文件是否存在，如存在则返回对应路径，如不存在则返回null
 * @param checkPath - 需要检测的路径
 * @param returnPath - 需要返回的路径
 */
function getAccessPath(checkPath: string, returnPath: string): Promise<string | null> {
  return new Promise((resolve) => {
    fs.access(checkPath, (err) => {
      if (!err) {
        resolve(returnPath);
      } else {
        fs.access(`${checkPath}.js`, (err2) => {
          if (!err2) {
            resolve(returnPath);
          } else {
            resolve(null);
          }
        });
      }
    });
  });
}
